import { observable, action, toJS } from "mobx";
import peers from '../lib/loadPeers';
import Store from 'electron-store';
import io from 'socket.io-client';
import {ipcRenderer} from 'electron';
const store = new Store();

let socket = null;

class User {
    @observable list = peers || {};
    @observable peer = null;
    @observable userInfo = null;

    constructor () {
        this.initUser();
    }

    @action
    async initUser () {
        let info = ipcRenderer.sendSync('self_info', 'ping')
        this.userInfo = info;
    }

    @action
    addUser (user) {
        const map = toJS(this.list);

        // 是否是修改了ip的用户(自己的本地id是不变的)
        let isOldUser = false;
        for(let i in map) {
            if (map[i].id === user.id) {
                isOldUser = true;
                map[i] = user;
                map[i].is_online = true;
            }
        }
        if (!isOldUser) {
            map[user.ip] = user;
            map[user.ip].is_online = true;
        }
        this.list = map;
        store.set('ft.peers', toJS(this.list));
    }

    @action
    onSelectPeer (peer) {
        this.peer = peer;
        if (socket) {
            socket.disconnect();
            socket = null;
        }
        socket = io('http://'+peer.ip+':58168/msg');
        socket.on('connect', function(){
            console.log('con....');
        });
    }

    send (msg, type = 'text') {
        let ip = this.userInfo.ip;
        if (msg.type === 'text' || msg.type === 'image'){
            socket.connected && socket.emit('peerMsg', {ip, type: msg.type, msg: msg.content});
        } else {
            socket.connected && socket.emit('peerMsg', {ip, type, msg});
        }
    }

    isConnected () {
        return socket && socket.connected;
    }
}

export default new User();